package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop

import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.CommentListContract
import fm.dongman.animefm.contractlib.contract.MyContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.CommentEditTextDialog
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.CommentModel
import fm.dongman.modellib.source.CommentListRepository
import fm.dongman.presenterlib.presenter.CommentListPresenter
import kotlinx.android.synthetic.main.fragment_comment_list.*
import kotlinx.android.synthetic.main.item_comment_list.view.*
import org.jetbrains.anko.onClick

/**
 * 评论列表页面
 * Create as Administrator
 */
class CommentListFragment : BaseFragment(), CommentListContract.ICommentListView {

    private lateinit var mPresenter: CommentListContract.ICommentListPresenter // 评论列表数据控制器
    private var mFlagType: String = TYPE_MINE // 评论类型
    private var mFlagId: String? = null // 参数 id or null

    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mCommentListAdapter: CommentListAdapter // 评论列表适配器
    private val mCommentList: ArrayList<IModel.ICommentModel> = ArrayList() // 评论列表数据集合

//    private lateinit var mMyCommentListAdapter: CommentListAdapter // 我的评论他人评论列表适配器
//    private val mMyCommentList: ArrayList<IModel.ICommentModel> = ArrayList() // 评论列表数据

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_comment_list, container, false)
        CommentListPresenter(this, Injection.provideCommentListRepository())
        return view
    }

    override fun requestListData(page: Int) {
        mPresenter.getComments(1, null, mFlagType, mFlagId)
        mScrollListener.clearPage()
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mFlagType = arguments.getString(FLAG_TYPE)
            mFlagId = arguments.getString(FLAG_ID)
        }
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun bindData() {
        bindToolbar()
        bindCommentList()
    }

    /**
     * 绑定 Toolbar
     */
    private fun bindToolbar() {
        when (mFlagType) {
            TYPE_MINE -> {
                mCommentListToolbar.title = getString(R.string.str_my_comment)
            }
            TYPE_OTHERS -> {
                mCommentListToolbar.visibility = View.GONE
            }
            else -> {
                mCommentListToolbar.title = getString(R.string.str_all_comments)
            }
        }
        mCommentListToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mCommentListToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
    }

    /**
     * 绑定评论列表
     */
    private fun bindCommentList() {
//        if(TYPE_OTHERS==mFlagType || TYPE_MINE==mFlagType){
//            mMyCommentListAdapter = CommentListAdapter(activity, mCommentList)
//            mCommentListRecycler.adapter = mMyCommentListAdapter
//            mCommentListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
//            mCommentListRecycler.addOnScrollListener(object : LoadMoreRecyclerOnScrollListener(mCommentListRecycler.layoutManager){
//                override fun onLoadMore(currentPage: Int) {
//                    mPresenter.getComments(currentPage, null, mFlagType, mFlagId)
//                }
//            })
//            mPresenter.getComments(1, null, mFlagType, mFlagId)
//            return
//        }

        mCommentListAdapter = CommentListAdapter(activity, mCommentList)
        mCommentListRecycler.adapter = mCommentListAdapter
        mCommentListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mCommentListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter.getComments(currentPage, null, mFlagType, mFlagId)
            }
        }
        mCommentListRecycler.addOnScrollListener(mScrollListener)
        if (mFlagType == TYPE_OTHERS)
            requestListData(1)
    }

    override fun setPresenter(presenter: CommentListContract.ICommentListPresenter) {
        mPresenter = presenter
    }

    override fun showRefreshFailed() {
        onStateChanged(MultiStateLayout.EMPTY)
        ToastHelper.getInstance(activity).showError("评论列表页面" + getString(R.string.str_refresh_failed))
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showCommentList(comments: List<IModel.ICommentModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        if (TYPE_OTHERS == mFlagType || TYPE_MINE == mFlagType) {
            mCommentListRecycler.adapter = fm.dongman.animefm.view.adapter.CommentListAdapter(activity, comments)
            mCommentListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            mCommentListAdapter.notifyDataSetChanged()
            return
        }
        mCommentList.clear()
        mCommentList.addAll(comments)
        mCommentListAdapter.notifyDataSetChanged()
    }

    override fun showMoreComments(comments: List<IModel.ICommentModel>) {
        mCommentList.addAll(comments)
        mCommentListAdapter.notifyDataSetChanged()
    }

    override fun showSupportSucceed() {
        Toast.makeText(activity, getString(R.string.str_support_succeed), Toast.LENGTH_SHORT).show()
    }

    override fun showSupportFailed() {
        Toast.makeText(activity, getString(R.string.str_support_failed), Toast.LENGTH_SHORT).show()
    }

    override fun showDeleteCommentState(state: Boolean) {
        ToastHelper.getInstance(activity).showWarn("删除" + if (state) "成功" else "失败")
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    /**
     * 切换状态
     */
    private fun onStateChanged(state: Int) {
        mCommentListMultiState?.changeState(state)
    }

    companion object {
        private val FLAG_ID = "fm.dongman.animefm.flag.commentList.id"
        private val FLAG_TYPE = "fm.dongman.animefm.flag.commentList.type"

        val TYPE_COMIC = CommentListRepository.SUBJECT // 动漫评论
        val TYPE_SHEET = CommentListRepository.MANDAN // 漫单评论
        val TYPE_ARTICLE = CommentListRepository.ARTICLE // 文章评论
        val TYPE_MINE = CommentListRepository.USER_OWN // 我的评论
        val TYPE_OTHERS = CommentListRepository.USER_OTHERS // 别人的评论

        /**
         * 获取实例
         *
         * @param flagType 类型
         * @param flagId   参数
         * @return CommentListFragment
         */
        fun getInstance(flagType: String, flagId: String?): CommentListFragment {
            val fragment = CommentListFragment()
            val bundle = Bundle()
            bundle.putString(FLAG_TYPE, flagType)
            bundle.putString(FLAG_ID, flagId)
            fragment.arguments = bundle
            return fragment
        }
    }

    /**
     * 评论列表适配器
     */
    private inner class CommentListAdapter(private val mContext: Context, private val mData: List<IModel.ICommentModel>)
        : RecyclerView.Adapter<CommentListAdapter.CommentListViewHolder>() {

        @SuppressLint("InflateParams")
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CommentListViewHolder =
                CommentListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_comment_list_all, null))

        override fun onBindViewHolder(holder: CommentListViewHolder?, position: Int) {
            val comment = mData[position] as CommentModel
            Glide.with(mContext)
                    .load(comment.user.avatarUrl)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 18))
                    .placeholder(R.mipmap.avatar)
                    .into(holder!!.mAvatar)
            holder.mUserName.text = comment.user.userName
            holder.mCreateTime.text = comment.createTime
            holder.mContent.text = comment.content

            if (mFlagType != TYPE_MINE && mFlagType != TYPE_OTHERS) {
                holder.itemView.onClick {

                    val moreDialog = BottomSheetDialog(mContext, R.style.Theme_Design_BottomSheetDialog_MyBottomSheet)
                    val view = View.inflate(mContext, R.layout.dialog_anime_comment_more, null)
                    val reply = view.findViewById(R.id.mTvCommentListReply)
                    val user = view.findViewById(R.id.mTvCommentListUserName)
                    val copyContent = view.findViewById(R.id.mTvCommentListCopy)
                    val cancel = view.findViewById(R.id.mTvCommentListCancel)
                    //回复
                    reply.onClick {
                        //是否登陆
                        if (MyContract.USER_ID == null) {
                            ToastHelper.getInstance(mContext).showError("尚未登录")
                            val i = Intent(mContext, SingleActivity::class.java)
                            i.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_LOGIN)
                            ActivityHelper.startActivity(mContext as Activity, i)
                            return@onClick
                        }
                        CommentEditTextDialog.Builder(mContext)
                                .setTitle("评论")
                                .setCommentType(mFlagType)
                                .setSubjectId(mFlagId)
                                .setOnButtonClickListenr(object :CommentEditTextDialog.Builder.OnButtonClickListener{
                                    override fun onCommit(inputContent: String?) {
                                    }

                                    override fun onCanceled() {
                                    }

                                    override fun onCommitSucceed() {
                                        requestListData(1)
                                    }

                                    override fun onCommitFailed() {
                                    }
                                })
                                .build().show()
                        moreDialog.dismiss()
                    }
                    //查看用户
                    user.onClick {
                        ActivityHelper.startActivity(mContext as Activity, SingleActivity::class.java, mapOf(
                                Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_INFO),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, comment.user.userId)), false)
                        moreDialog.dismiss()
                    }
                    //复制内容
                    copyContent.onClick {
                        val manager = mContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        manager.primaryClip = ClipData.newPlainText("comment", comment.content)
                        ToastHelper.getInstance(mContext).showSucceed("已复制")
                        moreDialog.dismiss()
                    }
                    //取消
                    cancel.onClick {
                        moreDialog.dismiss()
                    }
                    moreDialog.setContentView(view)
                    moreDialog.show()
                }
            }
        }

        override fun getItemCount(): Int = mData.size

        private inner class CommentListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val mAvatar: ImageView = itemView.mIvTheLatestCommentsPic     //用户头像
            val mContent: TextView = itemView.mTvTheLatestComments          //内容
            val mCreateTime: TextView = itemView.mTvTheLatestCommentsTime       //创建时间
            val mUserName: TextView = itemView.mTvTheLatestCommentsUserName         //用户名
            val mSplitLine: View = itemView.mViewCommentLine
        }

    }
}

